package main

import (
	"context"
	"log/slog"
	"net/http"
	"time"

	"gitee.com/openeuler/uos-libvirtd-exporter/slogx"
	"gitee.com/openeuler/uos-libvirtd-exporter/slogx/middleware"
)

func appLoggerExample() {
	slogx.Setup(slogx.Config{
		Level:      slog.LevelDebug,
		Format:     "json",
		FilePath:   "./logs/app.log",
		WithStdout: true,
		AddSource:  true,
	})

	slogx.Debug("debug message", "key", "value")
	slogx.Info("user login", "user", "alice", "ip", "127.0.0.1")
	slogx.Warn("cache miss", "key", "session:123")
	slogx.Error("db connect failed", "err", "timeout")

	ctx := slogx.WithTraceID(context.Background(), "trace-xyz")
	slogx.InfoCtx(ctx, "request handled", "status", 200)
}

func middlewareExample() {
	slogx.Setup(slogx.Config{
		FilePath:   "./logs/http.log",
		Format:     "json",
		WithStdout: true,
		Level:      slog.LevelInfo,
	})

	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		_, err := w.Write([]byte("hello world"))
		if err != nil {
			slogx.Error("Failed to write response", "error", err)
		}
	})

	handler := middleware.HTTPMiddleware(mux)

	// 创建带超时配置的服务器而不是直接使用 http.ListenAndServe
	server := &http.Server{
		Addr:              ":8080",
		Handler:           handler,
		ReadHeaderTimeout: 3 * time.Second,
		ReadTimeout:       5 * time.Second,
		WriteTimeout:      10 * time.Second,
		IdleTimeout:       120 * time.Second,
	}

	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		slogx.Error("Server listen failed", "error", err)
	}
}

func main() {
	appLoggerExample()

	// 在单独的 goroutine 中运行服务器以便能够优雅地关闭
	go middlewareExample()

	// 程序持续运行一段时间以允许测试
	time.Sleep(30 * time.Second)
}
